import time
import pyaudio
import wave
import sys
import threading


class myThread (threading.Thread):
    def __init__(self, path, p):
        threading.Thread.__init__(self)
        self.path = path
        self.p = p

    def run(self):
        self.wf = wave.open("./voice/" + self.path + ".wav", 'rb')
        self.CHUNK = 1024
        stream = self.p.open(format=self.p.get_format_from_width(self.wf.getsampwidth()),
                             channels=self.wf.getnchannels(),
                             rate=self.wf.getframerate(),
                             output=True)
        data = self.wf.readframes(self.CHUNK)
        while data != b'':  # time:3.3 second
            stream.write(data)
            data = self.wf.readframes(self.CHUNK)
        stream.stop_stream()
        stream.close()
        self.p.terminate()

class Voice():
    def __init__(self):
        # if len(sys.argv) < 2:
        #     print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
        #     sys.exit(-1)
        self.p = pyaudio.PyAudio() # time:1.4 second

    def audioPlay(self, path):
        self.path = path
        try:
            self.thread1 = myThread(self.path, self.p)
        except:
            print("Error: 无法启动线程")
        self.thread1.start()